import React, { useState, useEffect } from 'react';
import { 
  Typography, Tabs, List, Card, Button, Tag, Space, 
  Divider, Breadcrumb, Empty, Spin, Badge, Descriptions
} from 'antd';
import { Link } from 'react-router-dom';
import { 
  ShoppingOutlined, 
  ClockCircleOutlined, 
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';

const { Title, Text, Paragraph } = Typography;
const { TabPane } = Tabs;

// 模拟订单数据
const mockOrders = [
  {
    id: '1001',
    orderNumber: 'SK20230601001',
    status: 'pending',
    createTime: '2023-06-01 13:24:56',
    paymentTime: null,
    shipmentTime: null,
    completionTime: null,
    totalPrice: 6999,
    paymentMethod: '支付宝',
    address: {
      name: '张三',
      phone: '13800138000',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '科技园南区T3栋501室'
    },
    items: [
      {
        id: 1,
        productId: 1,
        name: 'iPhone 13 Pro',
        price: 6999,
        originalPrice: 7999,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLe2mALDSVAAF0enjwEQA837.jpg',
        isSecKill: true
      }
    ]
  },
  {
    id: '1002',
    orderNumber: 'SK20230528002',
    status: 'paid',
    createTime: '2023-05-28 18:13:22',
    paymentTime: '2023-05-28 18:15:40',
    shipmentTime: null,
    completionTime: null,
    totalPrice: 2098,
    paymentMethod: '微信支付',
    address: {
      name: '李四',
      phone: '13900139000',
      province: '广东省',
      city: '深圳市',
      district: '福田区',
      detail: '中心区福华路333号'
    },
    items: [
      {
        id: 2,
        productId: 6,
        name: 'Switch游戏机',
        price: 1799,
        originalPrice: 2099,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLeviAFdHhAAErLFJZZsg037.jpg',
        isSecKill: true
      },
      {
        id: 3,
        productId: 2,
        name: '蓝牙耳机',
        price: 299,
        originalPrice: 299,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/A3/wKj0iWTRBW-ARRIuAAG1qClJfLY822.jpg',
        isSecKill: false
      }
    ]
  },
  {
    id: '1003',
    orderNumber: 'SK20230520003',
    status: 'shipped',
    createTime: '2023-05-20 10:11:32',
    paymentTime: '2023-05-20 10:12:15',
    shipmentTime: '2023-05-21 09:05:20',
    completionTime: null,
    totalPrice: 199,
    paymentMethod: '支付宝',
    logistics: {
      company: '顺丰速运',
      trackingNumber: 'SF1234567890'
    },
    address: {
      name: '王五',
      phone: '13700137000',
      province: '广东省',
      city: '广州市',
      district: '天河区',
      detail: '天河路123号'
    },
    items: [
      {
        id: 4,
        productId: 3,
        name: '小米手环7',
        price: 199,
        originalPrice: 249,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4D/59/wKj0iGTcxUmAQwAGAAF_rOyZvxw488.jpg',
        isSecKill: true
      }
    ]
  },
  {
    id: '1004',
    orderNumber: 'SK20230510004',
    status: 'completed',
    createTime: '2023-05-10 20:20:20',
    paymentTime: '2023-05-10 20:21:30',
    shipmentTime: '2023-05-11 10:00:00',
    completionTime: '2023-05-13 14:15:20',
    totalPrice: 4299,
    paymentMethod: '微信支付',
    logistics: {
      company: '圆通速递',
      trackingNumber: 'YT9876543210'
    },
    address: {
      name: '赵六',
      phone: '13600136000',
      province: '浙江省',
      city: '杭州市',
      district: '西湖区',
      detail: '文三路158号'
    },
    items: [
      {
        id: 5,
        productId: 5,
        name: 'iPad Air',
        price: 4299,
        originalPrice: 4799,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/23/wKj0iWTLerqAHFU8AAFoT7tZJb4297.jpg',
        isSecKill: true
      }
    ]
  },
  {
    id: '1005',
    orderNumber: 'SK20230505005',
    status: 'canceled',
    createTime: '2023-05-05 13:10:15',
    paymentTime: null,
    shipmentTime: null,
    completionTime: null,
    cancelTime: '2023-05-05 13:40:20',
    totalPrice: 2799,
    paymentMethod: null,
    address: {
      name: '张三',
      phone: '13800138000',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '科技园南区T3栋501室'
    },
    items: [
      {
        id: 6,
        productId: 8,
        name: 'Apple Watch Series 7',
        price: 2799,
        originalPrice: 3199,
        quantity: 1,
        imageUrl: 'https://img01.71360.com/file/read/www/M00/4C/24/wKj0iWTLevSAQ6U3AAFZZzAuwUg396.jpg',
        isSecKill: true
      }
    ]
  }
];

const OrderPage: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [orders, setOrders] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState('all');

  useEffect(() => {
    // 模拟数据加载
    setLoading(true);
    setTimeout(() => {
      setOrders(mockOrders);
      setLoading(false);
    }, 500);
  }, []);

  const filteredOrders = activeTab === 'all' 
    ? orders 
    : orders.filter(order => {
        switch (activeTab) {
          case 'pending':
            return order.status === 'pending';
          case 'paid':
            return order.status === 'paid';
          case 'shipped':
            return order.status === 'shipped';
          case 'completed':
            return order.status === 'completed';
          case 'canceled':
            return order.status === 'canceled';
          default:
            return true;
        }
      });

  const handleTabChange = (key: string) => {
    setActiveTab(key);
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'pending':
        return <Tag color="orange" icon={<ClockCircleOutlined />}>待付款</Tag>;
      case 'paid':
        return <Tag color="blue" icon={<CheckCircleOutlined />}>已付款</Tag>;
      case 'shipped':
        return <Tag color="purple" icon={<ShoppingOutlined />}>已发货</Tag>;
      case 'completed':
        return <Tag color="green" icon={<CheckCircleOutlined />}>已完成</Tag>;
      case 'canceled':
        return <Tag color="red" icon={<CloseCircleOutlined />}>已取消</Tag>;
      default:
        return <Tag color="default" icon={<ExclamationCircleOutlined />}>未知状态</Tag>;
    }
  };

  const getActionButtons = (order: any) => {
    switch (order.status) {
      case 'pending':
        return (
          <Space>
            <Button type="primary" size="small">付款</Button>
            <Button danger size="small">取消订单</Button>
          </Space>
        );
      case 'paid':
        return (
          <Space>
            <Button size="small">查看订单</Button>
            <Button size="small">联系客服</Button>
          </Space>
        );
      case 'shipped':
        return (
          <Space>
            <Button type="primary" size="small">确认收货</Button>
            <Button size="small">查看物流</Button>
          </Space>
        );
      case 'completed':
        return (
          <Space>
            <Button type="primary" size="small">再次购买</Button>
            <Button size="small">评价</Button>
          </Space>
        );
      case 'canceled':
        return (
          <Button type="primary" size="small">再次购买</Button>
        );
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className="order-page">
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>我的订单</Breadcrumb.Item>
      </Breadcrumb>
      
      <Title level={2}>我的订单</Title>
      
      <Tabs activeKey={activeTab} onChange={handleTabChange}>
        <TabPane tab="全部订单" key="all">
          {renderOrderList(filteredOrders)}
        </TabPane>
        <TabPane 
          tab={
            <Badge count={orders.filter(o => o.status === 'pending').length} size="small" offset={[5, 0]}>
              待付款
            </Badge>
          } 
          key="pending"
        >
          {renderOrderList(filteredOrders)}
        </TabPane>
        <TabPane tab="已付款" key="paid">
          {renderOrderList(filteredOrders)}
        </TabPane>
        <TabPane tab="已发货" key="shipped">
          {renderOrderList(filteredOrders)}
        </TabPane>
        <TabPane tab="已完成" key="completed">
          {renderOrderList(filteredOrders)}
        </TabPane>
        <TabPane tab="已取消" key="canceled">
          {renderOrderList(filteredOrders)}
        </TabPane>
      </Tabs>
    </div>
  );

  function renderOrderList(orderList: any[]) {
    if (orderList.length === 0) {
      return (
        <Empty description="暂无订单" />
      );
    }

    return (
      <List
        dataSource={orderList}
        renderItem={order => (
          <Card style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Space>
                <Text type="secondary">订单号: {order.orderNumber}</Text>
                <Text type="secondary">下单时间: {order.createTime}</Text>
              </Space>
              {getStatusTag(order.status)}
            </div>
            
            <Divider style={{ margin: '12px 0' }} />
            
            <List
              dataSource={order.items}
              renderItem={(item: any) => (
                <List.Item>
                  <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                    <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                      <img 
                        src={item.imageUrl} 
                        alt={item.name} 
                        style={{ width: 60, height: 60, marginRight: 16 }}
                      />
                      <div>
                        <Link to={`/products/${item.productId}`}>
                          <Text strong>{item.name}</Text>
                        </Link>
                        {item.isSecKill && (
                          <Tag color="red" style={{ marginLeft: 8 }}>秒杀</Tag>
                        )}
                        <div>
                          <Text type="secondary">¥{item.price} × {item.quantity}</Text>
                        </div>
                      </div>
                    </div>
                    
                    <div style={{ textAlign: 'right' }}>
                      <Text type="danger">¥{(item.price * item.quantity).toFixed(2)}</Text>
                    </div>
                  </div>
                </List.Item>
              )}
            />
            
            <Divider style={{ margin: '12px 0' }} />
            
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                {order.status !== 'pending' && order.status !== 'canceled' && (
                  <Space>
                    <Text type="secondary">支付方式: {order.paymentMethod}</Text>
                    {order.logistics && (
                      <Text type="secondary">物流: {order.logistics.company} {order.logistics.trackingNumber}</Text>
                    )}
                  </Space>
                )}
              </div>
              
              <div>
                <Space direction="vertical" align="end">
                  <Text>共 {order.items.reduce((sum: number, item: any) => sum + item.quantity, 0)} 件商品 
                    合计: <span style={{ color: '#ff4d4f', fontSize: 16, fontWeight: 'bold' }}>¥{order.totalPrice.toFixed(2)}</span>
                  </Text>
                  {getActionButtons(order)}
                </Space>
              </div>
            </div>
          </Card>
        )}
      />
    );
  }
};

export default OrderPage; 